<template>
  <div class="selectors full">
    <selector v-model="currentTable" label="当前表" :showAllOption="false" :columns="tables" />
  </div>
  <component :is="component" :table="currentTable" />

  <Tabbar v-model="currentComponent">
    <TabbarItem name="columns">
      <template #icon><i class="fa fa-columns"></i></template> 字段
    </TabbarItem>
    <TabbarItem name="datas" icon="points">数据</TabbarItem>
    <TabbarItem name="script">
      <template #icon><i class="fa fa-terminal"></i></template> 脚本
    </TabbarItem>
    <TabbarItem name="dml">
      <template #icon><i class="fa fa-code"></i></template> DML
    </TabbarItem>
  </Tabbar>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { useRoute } from 'vue-router';
  import { ref, inject, computed, watch, onMounted, defineAsyncComponent } from 'vue';
  import { Tabbar, TabbarItem } from 'vant';

  const $store = useStore();
  const $route = useRoute();
  const $http = inject('$http');

  const components = {
    columns: defineAsyncComponent(() => import('./components/Columns.vue')),
    datas: defineAsyncComponent(() => import('./components/Datas.vue')),
    script: defineAsyncComponent(() => import('./components/Scripts.vue')),
    dml: defineAsyncComponent(() => import('./components/DML.vue'))
  };

  const tables = ref([]);
  const tempDatas = ref([]);
  const currentTable = ref('');
  const currentComponent = ref('columns');

  const component = computed(() => components[currentComponent.value]);

  function getTables() {
    if (!$route.params.dbIndex || !$route.params.schema) {
      return;
    }

    tables.value.length = 0;

    $http.get(`/api/db/${$route.params.dbIndex}/${$route.params.schema}/tables`).then(res => {
      tables.value = tempDatas.value = (res.datas || []).map(t => t.table_name);

      if (tables.value.length > 0) {
        currentTable.value = res.datas[0].table_name;
      }
    });
  }

  watch($route, () => {
    getTables();
  });

  onMounted(() => {
    getTables();

    $store.commit('navigateBack', { path: '/dbs' });
    $store.commit('navigateTitle', `数据库详情 - ${$route.params.schema}`);
  });
</script>

<style lang="less" scoped></style>
